<script setup lang="ts">
import { danmus as danmusData, getDanmuData, customDanmus } from "./danmu.ts";
import { onMounted, onUnmounted, reactive, ref, computed, onBeforeUnmount } from "vue";
import VueDanmaku from "vue3-danmaku";
import { getActivityDetailApi, getActivityCommentApi, createActivityCommentDataApi } from "@@/apis/activity"
import { getToken } from "@@/utils/cache/cookies"
import { Position } from "@element-plus/icons-vue"

defineOptions({
  name: "Danmaku"
});

const route = useRoute()
const danmaku = ref();
// const danmus = ref<any[]>(getDanmuData());
const danmus = ref<any[]>();
const danmuMsg = ref<string>("");
let timer = 0;
const config = reactive({
  channels: 0, // 轨道数量，为0则弹幕轨道数会撑满容器
  useSlot: true, // 是否开启slot
  loop: true, // 是否开启弹幕循环
  speeds: 100, // 弹幕速度，实际为弹幕滚动完一整屏的秒数，值越小速度越快
  fontSize: 20, // 文本模式下的字号
  top: 30, // 弹幕轨道间的垂直间距
  right: 20, // 同一轨道弹幕的水平间距
  debounce: 100, // 弹幕刷新频率（多少毫秒插入一条弹幕，建议不小于50）
  randomChannel: true // 随机弹幕轨道
});

const backgroundUrl = ref(null)
const fontColor = ref(null)



onUnmounted(() => {
  window.onresize = null;
});

function play(type: string) {
  switch (type) {
    case "play":
      danmaku.value.play();
      break;
    case "pause":
      danmaku.value.pause();
      break;
    case "stop":
      danmaku.value.stop();
      break;
    case "show":
      danmaku.value.show();
      break;
    case "hide":
      danmaku.value.hide();
      break;
    case "reset":
      danmaku.value.reset();
      break;
    default:
      break;
  }
}

function switchSlot(slot: boolean) {
  config.useSlot = slot;
  danmus.value = slot ? getDanmuData() : danmusData;

  setTimeout(() => {
    danmaku.value.stop();
    danmaku.value.play();
  });
}
function speedsChange(val: number) {
  if (config.speeds <= 10 && val === -10) {
    return;
  }
  config.speeds += val;
  danmaku.value.reset();
}
function fontChange(val: number) {
  config.fontSize += val;
  danmaku.value.reset();
}
function channelChange(val: number) {
  if (!config.channels && val === -1) {
    return;
  }
  config.channels += val;
}
function resizeHandler() {
  if (timer) clearTimeout(timer);
  timer = window.setTimeout(() => {
    danmaku.value.resize();
  }, 500);
}
function addDanmu() {
  if (!danmuMsg.value) return;
  const _danmuMsg = config.useSlot
    ? {
        avatar: "https://i.loli.net/2021/01/17/xpwbm3jKytfaNOD.jpg",
        name: "你",
        text: danmuMsg.value
      }
    : danmuMsg.value;
  danmaku.value.add(_danmuMsg);
  danmuMsg.value = "";

  const token = getToken()
  const params = {
    token,
    activity_id: route.query.id,
    content: _danmuMsg.text,
    comment_id: [],
    status: '',
    type: 1
  }
  createActivityCommentDataApi(params).then(({ data }) => {
    ElMessage.success("弹幕发布成功")
    getCommentData()
  }).catch(() => {

  }).finally(() => {
    // loading.value = false
  })
}


function getActivityDetail() {
  const params = {
    activity_id: route.query.id
  }
  getActivityDetailApi(params).then((res) => {
    if (res.data && res.data.image.length > 0) {
      backgroundUrl.value = res.data.image
      fontColor.value = res.data.font_color
      updateDocumentTitle(res.data.title)
      // background.background = ' red'
    }
  })
}
let winHei = window.innerHeight -81
const backgroundStyle = computed( () => ({
  background: `url(${backgroundUrl.value})`,
  backgroundSize: 'cover', // 可选，设置背景图片大小
  backgroundPosition: 'center', // 可选，设置背景图片位置
  width: '100%', // 可选，设置容器宽度
  height: winHei + 'px', // 可选，设置容器高度
}))

const fontColorStyle = computed( () => ({
  color: `${fontColor.value}`,
}))

function getCommentData() {
  getActivityCommentApi({
    type: 1,
    page: 1,
    page_size: 10,
    activity_id: route.query.id
  }).then(({ data }) => {
    if (data.list && data.list.length > 0) {
      const danmusData = []
      data.list.forEach(item=> {
        const randomIndex = Math.floor(Math.random() * customDanmus.length)
        const comment = {
          avatar: customDanmus[randomIndex].avatar,
          name: '匿名用户',
          text: ""
        }
        comment.text = item.content
        danmusData.push(comment)
      })
      danmus.value = [...danmusData]
    }
  }).catch(() => {
    danmus.value = []
  }).finally(() => {
  })
}
let intervalId
const startPolling = () => {
  intervalId = setInterval(getCommentData, 5000); // 每隔5秒请求一次数据
};

const stopPolling = () => {
  clearInterval(intervalId);
};

const updateDocumentTitle = (newTitle) => {
  document.title = newTitle;
}

onMounted(() => {
  getCommentData()
  getActivityDetail()
  window.onresize = () => resizeHandler();
  startPolling();
});

onBeforeUnmount(() => {
  stopPolling();
});
</script>
<template>
  <div>
    <div class="dm-content">
      <vue-danmaku
        ref="danmaku"
        v-model:danmus="danmus"
        class="demo"
        :style="backgroundStyle"
        isSuspend
        v-bind="config"
      >
        <!-- 弹幕slot -->
        <template v-slot:dm="{ danmu, index }">
          <div class="danmu-item">
            <img class="img" :src="danmu.avatar" />
            <!-- <span>{{ danmu.name }}{{ index }}：</span> -->
            <span :style="fontColorStyle">{{ danmu.text }}</span>
          </div>
        </template>
      </vue-danmaku>
      <div class="main">
        <el-input
          v-model="danmuMsg"
          size="large"
          placeholder="请输入弹幕"
          class="input-with-select"
          @keyup.enter="addDanmu"
        >
          <template #append>
            <el-button :icon="Position" size="large" @click="addDanmu">发送</el-button>
          </template>
          </el-input>
      </div>
      <div class="main" v-if="false">
        <p>
          播放：
          <el-button @click="play('play')">播放</el-button>
          <el-button @click="play('pause')">暂停</el-button>
          <el-button @click="play('stop')">停止</el-button>
        </p>
        <p>
          模式：
          <el-button @click="switchSlot(true)">弹幕 slot</el-button>
          <el-button @click="switchSlot(false)">普通文本</el-button>
        </p>
        <p>
          显示：
          <el-button @click="play('show')">显示</el-button>
          <el-button @click="play('hide')">隐藏</el-button>
        </p>
        <p>
          速度：
          <el-button @click="speedsChange(-10)">减速</el-button>
          <el-button @click="speedsChange(10)">增速</el-button>
          <span class="ml-5">当前速度：{{ config.speeds }}像素/s</span>
        </p>
        <p>
          字号：
          <el-button :disabled="config.useSlot" @click="fontChange(-1)">
            缩小
          </el-button>
          <el-button :disabled="config.useSlot" @click="fontChange(1)">
            放大
          </el-button>
          <span class="ml-5">当前字号：{{ config.fontSize }}px</span>
        </p>
        <p>
          轨道：
          <el-button @click="channelChange(-1)">-1</el-button>
          <el-button @click="channelChange(1)">+1</el-button>
          <el-button @click="channelChange(-config.channels)"> 填满 </el-button>
          <span class="ml-5">当前轨道：{{ config.channels }}</span>
        </p>
        <p class="flex">
          <el-input
            v-model="danmuMsg"
            type="text"
            placeholder="输入评论后，回车发送弹幕"
            @keyup.enter="addDanmu"
          />
        </p>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.demo {
  flex: 1;
  height: 100%;
  background: linear-gradient(45deg, #5ac381, #20568b);

  .danmu-item {
    display: flex;
    align-items: center;
    .img {
      width: 25px;
      height: 25px;
      margin-right: 5px;
      border-radius: 50%;
    }
  }
}

.main {
  flex: 1;

  p {
    margin-top: 10px;
  }
}
</style>
